<!-- ERP 产品列表 -->
<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="分类" prop="categoryId">
        <el-tree-select
          v-model="queryParams.categoryId"
          :data="categoryList"
          :props="defaultProps"
          check-strictly
          default-expand-all
          placeholder="请输入分类"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px"/>
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px"/>
          重置
        </el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['erp:product:create']"
        >
          <Icon icon="ep:plus" class="mr-5px"/>
          新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['erp:product:export']"
        >
          <Icon icon="ep:download" class="mr-5px"/>
          导出
        </el-button>
      </el-form-item>

     <div>
       <el-form-item >
         <el-upload class="upload-demo" :action="importUrl" :on-error="submitFormError" :show-file-list="false"
                    :on-exceed="handleExceed" :on-success="submitFormSuccess"  :headers="uploadHeaders" accept=".xlsx">
           <el-button type="primary">批量导入</el-button>
         </el-upload>
       </el-form-item>
     </div>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" border :data="list" :stripe="true" :show-overflow-tooltip="true">
<!--      <el-table-column label="条码" align="center" prop="barCode"/>-->
      <el-table-column label="名称"  prop="name" min-width="260"/>
      <!--      <el-table-column label="规格" align="center" prop="standard" />-->
      <el-table-column label="分类" align="center" prop="categoryName"/>
      <el-table-column label="部位"  prop="businessType" min-width="120">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.ERP_SALE_TYPE" :value="scope.row.businessType"/>
        </template>
      </el-table-column>
      <el-table-column label="单位" align="center" prop="unitName"/>
      <el-table-column label="品牌" align="center" prop="brandName" min-width="80"/>
<!--        <template #default="scope">-->
<!--          <dict-tag :type="DICT_TYPE.ERP_GLASS_BRAND" :value="scope.row.brandId"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="规格" align="left" prop="standard"/>
      <el-table-column label="VIN" align="center" prop="vin" min-width="120"/>
      <el-table-column label="工厂编号" align="center" prop="factoryNumber" min-width="120"/>
      <el-table-column label="OE" align="center" prop="oe" min-width="120"/>

      <el-table-column label="一级品牌" align="center" prop="amMainBrandName" min-width="120"/>
      <el-table-column label="二级品牌" align="center" prop="amBrandName" min-width="120"/>
      <el-table-column label="车系名称" align="center" prop="amSeriesName" min-width="120"/>
      <el-table-column label="销售车型" align="center" prop="amVehicleName" min-width="220"/>
      <el-table-column label="年款" align="center" prop="amYear"/>
      <el-table-column label="底盘号" align="center" prop="chassisModel"/>


      <el-table-column label="4S店价格" align="center" prop="flagshipPrice" min-width="100"/>
      <el-table-column label="综修厂价格" align="center" prop="repairFactoryPrice" min-width="100"/>
      <el-table-column label="零售价格" align="center" prop="retailPrice" min-width="100"/>
      <el-table-column label="保险价格" align="center" prop="insurancePrice" min-width="100"/>
      <el-table-column label="工时价格" align="center" prop="manHourPrice" min-width="100"/>
      <el-table-column label="玻璃+工时价" align="center" prop="glassAndManHourPrice" min-width="120"/>
      <el-table-column label="加工尺寸" align="center" prop="finishSize" min-width="100"/>
      <el-table-column label="夹层" align="center" prop="interlayerStatus" min-width="100">
        <template #default="scope">
<!--          <dict-tag :type="DICT_TYPE.ERP_PRODUCT_INTERLAYER_STATUS" :value="scope.row.interlayerStatus"/>-->
          <span>{{ scope.row.interlayerStatus === 1 || scope.row.interlayerStatus === null ? '无' : '有' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="自定义名称" align="center" prop="customName" min-width="100"/>
      <el-table-column label="共享状态" align="center" prop="shareStatus" min-width="100">
        <template #default="scope">
          <span>{{ scope.row.shareStatus === 1 || scope.row.shareStatus === null ? '不共享' : '共享' }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="采购价格"
        align="center"
        min-width="100"
        prop="purchasePrice"
        :formatter="erpPriceTableColumnFormatter"
      />
      <el-table-column
        label="销售价格"
        align="center"
        min-width="100"
        prop="salePrice"
        :formatter="erpPriceTableColumnFormatter"
      />
<!--      <el-table-column-->
<!--        label="最低价格"-->
<!--        align="center"-->
<!--        prop="minPrice"-->
<!--        :formatter="erpPriceTableColumnFormatter"-->
<!--      />-->
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" fixed="right" width="110">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['erp:product:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['erp:product:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ProductForm ref="formRef" @success="getList"/>
</template>

<script setup lang="ts">
import {dateFormatter} from '@/utils/formatTime'
import download from '@/utils/download'
import {ProductApi, ProductVO} from '@/api/erp/product/product'
import {ProductCategoryApi, ProductCategoryVO} from '@/api/erp/product/category'
import ProductForm from './ProductForm.vue'
import {DICT_TYPE} from '@/utils/dict'
import {defaultProps, handleTree} from '@/utils/tree'
import {erpPriceTableColumnFormatter} from '@/utils'
import {uploadAvatar} from "@/api/system/user/profile";
import type { UploadProps, UploadUserFile } from 'element-plus'
import {getAccessToken, getTenantId} from "@/utils/auth";
const importUrl =
  import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + '/erp/product/import-excel'
const uploadHeaders = ref({  Authorization: 'Bearer ' + getAccessToken(), 'tenant-id': getTenantId()}) // 上传 Header 头

/** ERP 产品列表 */
defineOptions({name: 'ErpProduct'})

const message = useMessage() // 消息弹窗
const {t} = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<ProductVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  categoryId: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const categoryList = ref<ProductCategoryVO[]>([]) // 产品分类列表

// 文件上传成功
const submitFormSuccess: UploadProps['onSuccess'] = (res: any): void => {
  message.success('上传成功')
}
// 文件数超出提示
const handleExceed: UploadProps['onExceed'] = (): void => {
  message.error(`上传文件数量不能超过${props.limit}个!`)
}
// 上传错误提示
const submitFormError: UploadProps['onError'] = (): void => {
  message.error('导入数据失败，请您重新上传！')
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ProductApi.getProductPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ProductApi.deleteProduct(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {
  }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ProductApi.exportProduct(queryParams)
    download.excel(data, '产品.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(async () => {
  await getList()
  // 产品分类
  const categoryData = await ProductCategoryApi.getProductCategorySimpleList()
  categoryList.value = handleTree(categoryData, 'id', 'parentId')
})
const route = useRoute();
onActivated(() => {

  //快捷添加
  let query = route.query;
  if (query.doType == 'handAdd') {
    formRef.value.open("create");
  }else if (query.doType == 'quickAdd'){
    formRef.value.open("create");
    let data = JSON.parse(query.data);
    formRef.value.formData.vin = data.vin;
    formRef.value.formData.brandId = data.brandId;
    formRef.value.formData.categoryId = data.categoryId;


    // formRef.value.formData.carType = data.amBrandName + data.amSeriesName + data.amVehicleName;

    // formRef.value.formData.amBrandName = data.amBrandName;
    // formRef.value.formData.amSeriesName = data.amSeriesName;
    // formRef.value.formData.amVehicleName = data.amVehicleName;
    // formRef.value.formData.amYear = data.amYear;
    // formRef.value.formData.amVehicleId = data.amVehicleId;
    // formRef.value.formData.amSeriesId = data.amSeriesId;
    // formRef.value.formData.amMainBrandName = data.amMainBrandName;
    // formRef.value.formData.amMainSeriesName = data.amMainSeriesName;
    // formRef.value.formData.amMainVehicleName = data.amMainVehicleName;
    // formRef.value.formData.amMainYear = data.amMainYear;
    // formRef.value.formData.amMainVehicleId = data.amMainVehicleId;
    // formRef.value.formData.amMainSeriesId = data.amMainSeriesId;
    // formRef.value.formData.amMainBrandId = data.amMainBrandId;
    // formRef.value.formData.amBrandId = data.amBrandId;
  }

  getList()
});
</script>
